package com.yuanxin.app.appjob.controller.pc;

import com.yuanxin.app.appjob.common.MVCViewName;
import com.yuanxin.app.appjob.appobject.PersonInfoAO;
import com.yuanxin.app.appjob.appobject.WorkReportAO;
import com.yuanxin.app.appjob.appobject.WorkingProgressAO;
import com.yuanxin.app.appjob.appobject.WorkingTableAO;
import com.yuanxin.app.appjob.entity.gen.WorkReportCriteria;
import com.yuanxin.app.appjob.entity.gen.WorkingProgressCriteria;
import com.yuanxin.app.appjob.entity.gen.WorkingTableCriteria;
import com.yuanxin.app.appjob.service.IWorkReportService;
import com.yuanxin.app.appjob.service.IWorkingProgressService;
import com.yuanxin.app.appjob.service.IWorkingTable;
import com.yuanxin.framework.logging.Logger;
import com.yuanxin.framework.logging.LoggerFactory;
import com.yuanxin.framework.service.ServiceResult;
import com.yuanxin.framework.util.DateTimeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import javax.validation.Valid;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 工作进展控制器。
 * 
 */
@Controller
@RequestMapping(value = "/pc/workingreport")
public class WorkingReportController {
	@Resource
	IWorkingProgressService workingProgressService;
	
	@Resource
	IWorkingTable workingTableService;
	
	@Resource
	IWorkReportService workReportService;

    private static Logger LOG = LoggerFactory.getLogger(WorkingProgressController.class);

    @RequestMapping(value = "", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView getHello(Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前时间传到前端
        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
		//将当前运用名称传到前端
        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
        ModelAndView mv = new ModelAndView();
        mv.addObject(model);
        
        return mv;
    } 
    
    @RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView list(Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前时间传到前端
        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
		//将当前运用名称传到前端
        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
        ModelAndView mv = new ModelAndView();
        Calendar cl = Calendar.getInstance();
    	cl.setFirstDayOfWeek(Calendar.SUNDAY); 
    	int week = cl.get(Calendar.WEEK_OF_YEAR); //获取周数
        WorkReportCriteria cc = new WorkReportCriteria();
        cc.createCriteria().andWeekNumEqualTo(Integer.toString(week));
        ServiceResult<List<WorkReportAO>> list = workReportService.selectByCriteria(cc);
        if(list!=null&& list.getData()!=null&& list.getData().size()>0){
        	model.addAttribute("datalist", list.getData());
        }else{
          model.addAttribute("datalist", new ArrayList());
        }
        mv.addObject(model);
        mv.setViewName(MVCViewName.APP_APPJOB_PC_WORKINGREPORT_WORKINGREPORT.toString());
        return mv;
    }
      
    @RequestMapping(value = "/llist/{weekNum}/{currentYear}", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView list(@PathVariable String weekNum , @PathVariable String currentYear ,Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前时间传到前端
        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
		//将当前运用名称传到前端
        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
       
        PersonInfoAO pf = (PersonInfoAO)request.getSession().getAttribute("currentUser");
        
                      ModelAndView mv = new ModelAndView();
        WorkReportCriteria cc = new WorkReportCriteria();
       //在页面中只显示本中心的信息
      
        
        if("weekNum".equals(weekNum) && "currentYear".equals(currentYear)){		
        	cc.createCriteria().andStaffDepartEqualTo(pf.getStaffDepart());	
        }else if("weekNum".equals(weekNum)){
        	cc.createCriteria().andCurrentYearEqualTo(currentYear).andStaffDepartEqualTo(pf.getStaffDepart());			
        }else if("currentYear".equals(currentYear)){
        	cc.createCriteria().andWeekNumEqualTo(weekNum).andStaffDepartEqualTo(pf.getStaffDepart());
        }else{
        	cc.createCriteria().andWeekNumEqualTo(weekNum).andCurrentYearEqualTo(currentYear).andStaffDepartEqualTo(pf.getStaffDepart());
        }
        
        ServiceResult<List<WorkReportAO>> list = workReportService.selectByCriteria(cc);
        if(list!=null&& list.getData()!=null&& list.getData().size()>0){
        	model.addAttribute("datalist", list.getData());
        }else{
        	model.addAttribute("datalist", new ArrayList());
        }
        
        mv.addObject(model);
        mv.setViewName(MVCViewName.APP_APPJOB_PC_WORKPROJECT_HISTORYRECORD.toString());
        return mv;
    }
    
	@RequestMapping(value = "/initialize", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object initialize(HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
       
        //将当前时间传到前端
		//将当前运用名称传到前端
        //初始化数据
        ServiceResult<String> result = new ServiceResult<String>();
        boolean flag = false;
        WorkingTableCriteria workcc=new WorkingTableCriteria();
    	workcc.createCriteria().andStatusDelEqualTo("0").andStatusEqualTo("0");
    	ServiceResult<List<WorkingTableAO>> worklist = workingTableService.selectByCriteria(workcc);
    	int jobnum=worklist.getData().size();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy");       
        Date date = new Date();       
        String formatDate = sdf.format(date); 
    	Calendar cl = Calendar.getInstance();
    	cl.setFirstDayOfWeek(Calendar.SUNDAY); 
    	int week = cl.get(Calendar.WEEK_OF_YEAR); //获取周数
    	int d = 0;
        if (cl.get(Calendar.DAY_OF_WEEK) == 1) {
            d = -6;
        } else {
            d = 2 - cl.get(Calendar.DAY_OF_WEEK);
        }
    	int dayOfWeek = cl.get(Calendar.DAY_OF_WEEK);
    	cl.add(Calendar.DAY_OF_WEEK, d);
    	String weekstart = new SimpleDateFormat("yyyy-MM-dd").format(cl.getTime());//本周开始
        cl.add(Calendar.DAY_OF_WEEK, 6);
        String weekend = new SimpleDateFormat("yyyy-MM-dd").format(cl.getTime());//本周结束
        cl.add(Calendar.DAY_OF_WEEK, 5);
        String nextFriday = new SimpleDateFormat("yyyy-MM-dd").format(cl.getTime());//下周五
    	//System.out.println("000000000000000");
        WorkingProgressCriteria progcc=new WorkingProgressCriteria();
        progcc.createCriteria().andWeekNumEqualTo(Integer.toString(week)).andCurrentYearEqualTo(formatDate);
        ServiceResult<List<WorkingProgressAO>> proglist = workingProgressService.selectByCriteria(progcc);
        if(proglist.getData().size()>0){
        	result.setSucceed(flag);
			result.setMsg("本周已经发起，请勿重复发起！");
        }else{
        
        try {    
        	for(int i=0; i<jobnum; i++){
        	String jobid=worklist.getData().get(i).getId();
        	WorkingProgressAO aa=new WorkingProgressAO();
        	aa.setJobId(Long.parseLong(jobid));
        	aa.setStartDate(weekstart);
        	aa.setEndDate(weekend);
        	aa.setWeekNum(Integer.toString(week));
        	aa.setCurrentYear(formatDate);
        	aa.setPlanDeadline(nextFriday);
        	workingProgressService.saveOrUpdate(aa);
        	}
        	flag=true;
        	 result.setSucceed(flag);
 			 result.setMsg("发起成功！可通知各业务人员开始反馈。");
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setSucceed(flag);
			result.setMsg("发起失败！");
		}
        }
        return result;
    }
}

